#!/usr/bin/env python3
"""
S3 Bucket Head Tool - HeadBucket API 演示工具

这个工具演示如何使用 HeadBucket API 检查桶的存在性和访问权限。

使用示例:
    python s3_bucket_head.py --name my-bucket
    python s3_bucket_head.py --names bucket1,bucket2,bucket3
    python s3_bucket_head.py --health-check
    python s3_bucket_head.py --format json
    python s3_bucket_head.py --verbose
"""

import argparse
import boto3
import json
import sys
import time
from datetime import datetime, timezone
from botocore.config import Config
from botocore.exceptions import ClientError, NoCredentialsError


class BucketHeadClient:
    """S3 桶检查客户端"""
    
    def __init__(self, endpoint_url='http://localhost:8000', 
                 access_key='AKIAIOSFODNN7EXAMPLE', 
                 secret_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
                 region='us-east-1'):
        """
        初始化桶检查客户端
        
        Args:
            endpoint_url: S3 服务端点
            access_key: AWS Access Key
            secret_key: AWS Secret Key
            region: AWS 区域
        """
        self.endpoint_url = endpoint_url
        self.access_key = access_key
        self.secret_key = secret_key
        self.region = region
        self._client = None
    
    def _get_client(self):
        """获取 S3 客户端"""
        if self._client is None:
            self._client = boto3.client(
                's3',
                endpoint_url=self.endpoint_url,
                aws_access_key_id=self.access_key,
                aws_secret_access_key=self.secret_key,
                region_name=self.region,
                config=Config(s3={'addressing_style': 'path'})
            )
        return self._client


    def head_single_bucket(self, bucket_name):
        """简单格式检查单个桶"""
        try:
            s3_client = self._get_client()
            start_time = time.time()
            response = s3_client.head_bucket(Bucket=bucket_name)
            end_time = time.time()
            
            print(f"✅ 桶存在且可访问: {bucket_name}")
            print(f"   ⏱️  响应时间: {(end_time - start_time) * 1000:.2f} ms")
            
            return True, "存在"
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            
            if error_code == 'NoSuchBucket':
                print(f"❌ 桶不存在: {bucket_name}")
                return False, "不存在"
            elif error_code == 'Forbidden':
                print(f"🔒 桶存在但无访问权限: {bucket_name}")
                return False, "无权限"
            else:
                error_msg = e.response['Error']['Message']
                print(f"❌ 检查失败 [{error_code}]: {bucket_name} - {error_msg}")
                return False, f"错误({error_code})"
        except NoCredentialsError:
            print("❌ 错误: 未找到 AWS 凭据")
            return False, "凭据错误"
        except Exception as e:
            print(f"❌ 未知错误: {bucket_name} - {e}")
            return False, "未知错误"
    
    def head_single_bucket_verbose(self, bucket_name):
        """详细格式检查单个桶"""
        try:
            s3_client = self._get_client()
            print("🔍 桶检查详细信息:")
            print("=" * 50)
            print(f"   🗂️  桶名称: {bucket_name}")
            print(f"   🌐 区域: {self.region}")
            print(f"   🔗 服务端点: {self.endpoint_url}")
            print(f"   📅 检查时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            print()
            
            start_time = time.time()
            response = s3_client.head_bucket(Bucket=bucket_name)
            end_time = time.time()
            
            response_time = (end_time - start_time) * 1000
            
            print(f"   ✅ 桶存在且可访问")
            print(f"   ⏱️  响应时间: {response_time:.2f} ms")
            print(f"   🌐 桶区域: {response.get('BucketRegion', '未知')}")
            
            # 显示响应头信息
            headers = response.get('ResponseMetadata', {}).get('HTTPHeaders', {})
            if headers:
                print(f"   📋 响应头:")
                for key, value in headers.items():
                    if key.lower() in ['server', 'x-amz-bucket-region', 'x-amz-request-id']:
                        print(f"      {key}: {value}")
            
            print(f"   📊 状态: 正常")
            
            return True, "存在"
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            print(f"   ❌ 检查失败:")
            print(f"      错误代码: {error_code}")
            print(f"      错误信息: {error_msg}")
            
            if error_code == 'NoSuchBucket':
                print(f"   📋 状态: 桶不存在")
                return False, "不存在"
            elif error_code == 'Forbidden':
                print(f"   📋 状态: 桶存在但无访问权限")
                return False, "无权限"
            else:
                print(f"   📋 状态: 错误({error_code})")
                return False, f"错误({error_code})"
        except NoCredentialsError:
            print("   ❌ 错误: 未找到 AWS 凭据")
            return False, "凭据错误"
        except Exception as e:
            print(f"   ❌ 未知错误: {e}")
            return False, "未知错误"
    
    def head_single_bucket_json(self, bucket_name):
        """JSON 格式检查单个桶"""
        try:
            s3_client = self._get_client()
            start_time = time.time()
            response = s3_client.head_bucket(Bucket=bucket_name)
            end_time = time.time()
            
            response_time = (end_time - start_time) * 1000
            
            result = {
                "success": True,
                "bucket_name": bucket_name,
                "status": "accessible",
                "response_time_ms": round(response_time, 2),
                "region": response.get('BucketRegion', 'unknown'),
                "check_time": datetime.now().isoformat()
            }
            
            # 添加响应头信息
            headers = response.get('ResponseMetadata', {}).get('HTTPHeaders', {})
            if headers:
                result["response_headers"] = {
                    key: value for key, value in headers.items()
                    if key.lower() in ['server', 'x-amz-bucket-region', 'x-amz-request-id']
                }
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return True, "存在"
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            if error_code == 'NoSuchBucket':
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "status": "not_found",
                    "error_code": error_code,
                    "error_message": error_msg,
                    "check_time": datetime.now().isoformat()
                }
            elif error_code == 'Forbidden':
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "status": "forbidden",
                    "error_code": error_code,
                    "error_message": error_msg,
                    "check_time": datetime.now().isoformat()
                }
            else:
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "status": "error",
                    "error_code": error_code,
                    "error_message": error_msg,
                    "check_time": datetime.now().isoformat()
                }
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return False, f"错误({error_code})"
        except NoCredentialsError:
            result = {
                "success": False,
                "error": "NoCredentials",
                "error_message": "未找到 AWS 凭据",
                "check_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return False, "凭据错误"
        except Exception as e:
            result = {
                "success": False,
                "error": "Unknown",
                "error_message": str(e),
                "check_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return False, "未知错误"


    def head_multiple_buckets(self, bucket_names):
        """简单格式批量检查桶"""
        results = {}
        success_count = 0
        
        print(f"🔍 批量检查 {len(bucket_names)} 个桶:")
        print("-" * 50)
        
        for bucket_name in bucket_names:
            success, status = self.head_single_bucket_simple(bucket_name)
            results[bucket_name] = status
            if success:
                success_count += 1
            print()
        
        # 显示汇总结果
        print("📊 批量检查结果:")
        print(f"   ✅ 可访问: {success_count}/{len(bucket_names)}")
        print(f"   ❌ 不可访问: {len(bucket_names) - success_count}/{len(bucket_names)}")
        
        # 按状态分组显示
        status_groups = {}
        for bucket, status in results.items():
            if status not in status_groups:
                status_groups[status] = []
            status_groups[status].append(bucket)
        
        for status, buckets in status_groups.items():
            if len(buckets) > 0:
                print(f"   {status}: {', '.join(buckets)}")
        
        return success_count == len(bucket_names)
    
    def head_multiple_buckets_verbose(self, bucket_names):
        """详细格式批量检查桶"""
        results = {}
        success_count = 0
        
        print("🔍 批量桶检查详细信息:")
        print("=" * 60)
        print(f"   📊 检查数量: {len(bucket_names)}")
        print(f"   🌐 区域: {self.region}")
        print(f"   🔗 服务端点: {self.endpoint_url}")
        print(f"   📅 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print()
        
        for i, bucket_name in enumerate(bucket_names, 1):
            print(f"   [{i}/{len(bucket_names)}] 检查桶: {bucket_name}")
            success, status = self.head_single_bucket_verbose(bucket_name)
            results[bucket_name] = status
            if success:
                success_count += 1
                print(f"   ✅ 成功")
            else:
                print(f"   ❌ 失败")
            print()
        
        # 显示汇总结果
        print("   📊 批量检查统计:")
        print(f"      • 总数量: {len(bucket_names)}")
        print(f"      • 可访问: {success_count}")
        print(f"      • 不可访问: {len(bucket_names) - success_count}")
        print(f"      • 成功率: {(success_count/len(bucket_names))*100:.1f}%")
        
        # 按状态分组显示
        status_groups = {}
        for bucket, status in results.items():
            if status not in status_groups:
                status_groups[status] = []
            status_groups[status].append(bucket)
        
        for status, buckets in status_groups.items():
            if len(buckets) > 0:
                print(f"      • {status}: {', '.join(buckets)}")
        
        print(f"   📅 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        
        return success_count == len(bucket_names)
    
    def head_multiple_buckets_json(self, bucket_names):
        """JSON 格式批量检查桶"""
        results = []
        success_count = 0
        
        for bucket_name in bucket_names:
            try:
                s3_client = self._get_client()
                start_time = time.time()
                response = s3_client.head_bucket(Bucket=bucket_name)
                end_time = time.time()
                
                response_time = (end_time - start_time) * 1000
                
                bucket_result = {
                    "bucket_name": bucket_name,
                    "success": True,
                    "status": "accessible",
                    "response_time_ms": round(response_time, 2),
                    "region": response.get('BucketRegion', 'unknown')
                }
                
                # 添加响应头信息
                headers = response.get('ResponseMetadata', {}).get('HTTPHeaders', {})
                if headers:
                    bucket_result["response_headers"] = {
                        key: value for key, value in headers.items()
                        if key.lower() in ['server', 'x-amz-bucket-region', 'x-amz-request-id']
                    }
                
                results.append(bucket_result)
                success_count += 1
                
            except ClientError as e:
                error_code = e.response['Error']['Code']
                error_msg = e.response['Error']['Message']
                
                bucket_result = {
                    "bucket_name": bucket_name,
                    "success": False,
                    "status": error_code.lower().replace('such', ''),
                    "error_code": error_code,
                    "error_message": error_msg
                }
                results.append(bucket_result)
            except Exception as e:
                bucket_result = {
                    "bucket_name": bucket_name,
                    "success": False,
                    "status": "error",
                    "error": "Unknown",
                    "error_message": str(e)
                }
                results.append(bucket_result)
        
        # 输出汇总结果
        summary = {
            "operation": "batch_head_buckets",
            "total_count": len(bucket_names),
            "success_count": success_count,
            "failed_count": len(bucket_names) - success_count,
            "success_rate": f"{(success_count/len(bucket_names))*100:.1f}%",
            "results": results,
            "check_time": datetime.now().isoformat()
        }
        
        print(json.dumps(summary, indent=2, ensure_ascii=False))
        return success_count == len(bucket_names)


    def health_check_buckets(self):
        """简单格式对所有桶进行健康检查"""
        try:
            s3_client = self._get_client()
            
            # 首先列出所有桶
            print("🔍 发现现有桶...")
            response = s3_client.list_buckets()
            buckets = [bucket['Name'] for bucket in response['Buckets']]
            
            if not buckets:
                print("📭 账户下没有桶")
                return True
            
            print(f"📚 发现 {len(buckets)} 个桶，开始健康检查:")
            print("=" * 60)
            
            # 对每个桶进行健康检查
            healthy_count = 0
            unhealthy_buckets = []
            
            for bucket_name in buckets:
                success, status = self.head_single_bucket_simple(bucket_name)
                if success:
                    healthy_count += 1
                else:
                    unhealthy_buckets.append((bucket_name, status))
                print()
            
            # 健康检查总结
            print("🏥 健康检查总结:")
            print(f"   ✅ 健康: {healthy_count}/{len(buckets)}")
            print(f"   ❌ 异常: {len(unhealthy_buckets)}/{len(buckets)}")
            
            if unhealthy_buckets:
                print(f"   异常桶详情:")
                for bucket, status in unhealthy_buckets:
                    print(f"      • {bucket}: {status}")
            
            # 整体健康状态
            if healthy_count == len(buckets):
                print("\n🎉 所有桶状态正常！")
                return True
            else:
                print(f"\n⚠️  有 {len(unhealthy_buckets)} 个桶存在问题")
                return False
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            print(f"❌ S3 错误 [{error_code}]: {error_msg}")
            return False
        except NoCredentialsError:
            print("❌ 错误: 未找到 AWS 凭据")
            return False
        except Exception as e:
            print(f"❌ 健康检查失败: {e}")
            return False
    
    def health_check_buckets_verbose(self):
        """详细格式对所有桶进行健康检查"""
        try:
            s3_client = self._get_client()
            
            print("🏥 桶健康检查详细信息:")
            print("=" * 70)
            print(f"   🌐 区域: {self.region}")
            print(f"   🔗 服务端点: {self.endpoint_url}")
            print(f"   📅 检查时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            print()
            
            # 首先列出所有桶
            print("   🔍 发现现有桶...")
            response = s3_client.list_buckets()
            buckets = [bucket['Name'] for bucket in response['Buckets']]
            
            if not buckets:
                print("   📭 账户下没有桶")
                return True
            
            print(f"   📚 发现 {len(buckets)} 个桶，开始健康检查:")
            print("   " + "=" * 60)
            
            # 对每个桶进行健康检查
            healthy_count = 0
            unhealthy_buckets = []
            
            for i, bucket_name in enumerate(buckets, 1):
                print(f"   [{i}/{len(buckets)}] 检查桶: {bucket_name}")
                success, status = self.head_single_bucket_verbose(bucket_name)
                if success:
                    healthy_count += 1
                    print(f"   ✅ 健康")
                else:
                    unhealthy_buckets.append((bucket_name, status))
                    print(f"   ❌ 异常")
                print()
            
            # 健康检查总结
            print("   🏥 健康检查统计:")
            print(f"      • 总桶数: {len(buckets)}")
            print(f"      • 健康数: {healthy_count}")
            print(f"      • 异常数: {len(unhealthy_buckets)}")
            print(f"      • 健康率: {(healthy_count/len(buckets))*100:.1f}%")
            
            if unhealthy_buckets:
                print(f"      • 异常桶详情:")
                for bucket, status in unhealthy_buckets:
                    print(f"        - {bucket}: {status}")
            
            # 整体健康状态
            if healthy_count == len(buckets):
                print(f"\n   🎉 所有桶状态正常！")
                return True
            else:
                print(f"\n   ⚠️  有 {len(unhealthy_buckets)} 个桶存在问题")
                return False
            
        except Exception as e:
            print(f"   ❌ 健康检查失败: {e}")
            return False
    
    def health_check_buckets_json(self):
        """JSON 格式对所有桶进行健康检查"""
        try:
            s3_client = self._get_client()
            
            # 首先列出所有桶
            response = s3_client.list_buckets()
            buckets = [bucket['Name'] for bucket in response['Buckets']]
            
            if not buckets:
                result = {
                    "success": True,
                    "operation": "health_check",
                    "total_buckets": 0,
                    "healthy_buckets": 0,
                    "unhealthy_buckets": 0,
                    "health_rate": "100.0%",
                    "message": "账户下没有桶",
                    "check_time": datetime.now().isoformat()
                }
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return True
            
            # 对每个桶进行健康检查
            bucket_results = []
            healthy_count = 0
            
            for bucket_name in buckets:
                try:
                    start_time = time.time()
                    response = s3_client.head_bucket(Bucket=bucket_name)
                    end_time = time.time()
                    
                    response_time = (end_time - start_time) * 1000
                    
                    bucket_result = {
                        "bucket_name": bucket_name,
                        "healthy": True,
                        "status": "accessible",
                        "response_time_ms": round(response_time, 2),
                        "region": response.get('BucketRegion', 'unknown')
                    }
                    
                    healthy_count += 1
                    
                except ClientError as e:
                    error_code = e.response['Error']['Code']
                    error_msg = e.response['Error']['Message']
                    
                    bucket_result = {
                        "bucket_name": bucket_name,
                        "healthy": False,
                        "status": error_code.lower().replace('such', ''),
                        "error_code": error_code,
                        "error_message": error_msg
                    }
                except Exception as e:
                    bucket_result = {
                        "bucket_name": bucket_name,
                        "healthy": False,
                        "status": "error",
                        "error": "Unknown",
                        "error_message": str(e)
                    }
                
                bucket_results.append(bucket_result)
            
            # 输出汇总结果
            unhealthy_count = len(buckets) - healthy_count
            health_rate = f"{(healthy_count/len(buckets))*100:.1f}%"
            
            result = {
                "success": healthy_count == len(buckets),
                "operation": "health_check",
                "total_buckets": len(buckets),
                "healthy_buckets": healthy_count,
                "unhealthy_buckets": unhealthy_count,
                "health_rate": health_rate,
                "bucket_results": bucket_results,
                "check_time": datetime.now().isoformat()
            }
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return healthy_count == len(buckets)
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            error_result = {
                "success": False,
                "error": error_code,
                "error_message": error_msg
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
            return False
        except NoCredentialsError:
            error_result = {
                "success": False,
                "error": "NoCredentials",
                "error_message": "未找到 AWS 凭据"
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
            return False
        except Exception as e:
            error_result = {
                "success": False,
                "error": "Unknown",
                "error_message": str(e)
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
            return False


    def performance_test(self, bucket_name, iterations=10):
        """简单格式性能测试"""
        print(f"⚡ 对桶 '{bucket_name}' 进行性能测试 ({iterations} 次):")
        print("-" * 50)
        
        response_times = []
        success_count = 0
        
        for i in range(iterations):
            try:
                s3_client = self._get_client()
                start_time = time.time()
                s3_client.head_bucket(Bucket=bucket_name)
                end_time = time.time()
                
                response_time = (end_time - start_time) * 1000
                response_times.append(response_time)
                success_count += 1
                
                print(f"第 {i+1:2d} 次: {response_time:6.2f} ms ✅")
                
            except Exception as e:
                print(f"第 {i+1:2d} 次: 失败 - {e} ❌")
        
        if response_times:
            avg_time = sum(response_times) / len(response_times)
            min_time = min(response_times)
            max_time = max(response_times)
            
            print("\n📊 性能统计:")
            print(f"   成功率: {success_count}/{iterations} ({success_count/iterations*100:.1f}%)")
            print(f"   平均响应时间: {avg_time:.2f} ms")
            print(f"   最快响应时间: {min_time:.2f} ms")
            print(f"   最慢响应时间: {max_time:.2f} ms")
        
        return success_count == iterations
    
    def performance_test_verbose(self, bucket_name, iterations=10):
        """详细格式性能测试"""
        print("⚡ 桶性能测试详细信息:")
        print("=" * 60)
        print(f"   🗂️  桶名称: {bucket_name}")
        print(f"   🌐 区域: {self.region}")
        print(f"   🔗 服务端点: {self.endpoint_url}")
        print(f"   📊 测试次数: {iterations}")
        print(f"   📅 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print()
        
        response_times = []
        success_count = 0
        
        for i in range(iterations):
            try:
                s3_client = self._get_client()
                start_time = time.time()
                s3_client.head_bucket(Bucket=bucket_name)
                end_time = time.time()
                
                response_time = (end_time - start_time) * 1000
                response_times.append(response_time)
                success_count += 1
                
                print(f"   [{i+1:2d}/{iterations}] {response_time:6.2f} ms ✅")
                
            except Exception as e:
                print(f"   [{i+1:2d}/{iterations}] 失败 - {e} ❌")
        
        if response_times:
            avg_time = sum(response_times) / len(response_times)
            min_time = min(response_times)
            max_time = max(response_times)
            
            print("\n   📊 性能统计:")
            print(f"      • 成功率: {success_count}/{iterations} ({success_count/iterations*100:.1f}%)")
            print(f"      • 平均响应时间: {avg_time:.2f} ms")
            print(f"      • 最快响应时间: {min_time:.2f} ms")
            print(f"      • 最慢响应时间: {max_time:.2f} ms")
            print(f"      • 响应时间范围: {max_time - min_time:.2f} ms")
        
        print(f"   📅 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        
        return success_count == iterations
    
    def performance_test_json(self, bucket_name, iterations=10):
        """JSON 格式性能测试"""
        response_times = []
        success_count = 0
        test_results = []
        
        for i in range(iterations):
            try:
                s3_client = self._get_client()
                start_time = time.time()
                s3_client.head_bucket(Bucket=bucket_name)
                end_time = time.time()
                
                response_time = (end_time - start_time) * 1000
                response_times.append(response_time)
                success_count += 1
                
                test_results.append({
                    "iteration": i + 1,
                    "success": True,
                    "response_time_ms": round(response_time, 2)
                })
                
            except Exception as e:
                test_results.append({
                    "iteration": i + 1,
                    "success": False,
                    "error": str(e)
                })
        
        # 计算统计信息
        stats = {}
        if response_times:
            stats = {
                "success_rate": f"{(success_count/iterations)*100:.1f}%",
                "average_response_time_ms": round(sum(response_times) / len(response_times), 2),
                "min_response_time_ms": round(min(response_times), 2),
                "max_response_time_ms": round(max(response_times), 2),
                "response_time_range_ms": round(max(response_times) - min(response_times), 2)
            }
        
        result = {
            "operation": "performance_test",
            "bucket_name": bucket_name,
            "iterations": iterations,
            "success_count": success_count,
            "failed_count": iterations - success_count,
            "test_results": test_results,
            "statistics": stats,
            "test_time": datetime.now().isoformat()
        }
        
        print(json.dumps(result, indent=2, ensure_ascii=False))
        return success_count == iterations


def parse_args():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(
        description='S3 HeadBucket API 演示工具',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  %(prog)s --name my-bucket                 # 检查单个桶
  %(prog)s --names bucket1,bucket2,bucket3 # 批量检查
  %(prog)s --health-check                   # 健康检查所有桶
  %(prog)s --name my-bucket --performance   # 性能测试
  %(prog)s --name my-bucket --verbose       # 详细输出
  %(prog)s --format json                    # JSON 格式输出
  %(prog)s --access-key KEY --secret-key SECRET  # 指定凭据
        """
    )
    
    parser.add_argument(
        '--host',
        default='http://localhost:8000',
        help='S3 服务端点 (默认: http://localhost:8000)'
    )
    
    parser.add_argument(
        '--access-key',
        default='AKIAIOSFODNN7EXAMPLE',
        help='AWS Access Key (默认: 测试密钥)'
    )
    
    parser.add_argument(
        '--secret-key',
        default='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
        help='AWS Secret Key (默认: 测试密钥)'
    )
    
    parser.add_argument(
        '--region',
        default='us-east-1',
        help='AWS 区域 (默认: us-east-1)'
    )
    
    parser.add_argument(
        '--format',
        choices=['simple', 'verbose', 'json'],
        default='simple',
        help='输出格式 (默认: simple)'
    )
    
    parser.add_argument(
        '--verbose',
        action='store_true',
        help='详细输出模式 (等同于 --format verbose)'
    )
    
    # 检查选项
    check_group = parser.add_mutually_exclusive_group(required=True)
    check_group.add_argument(
        '--name',
        help='要检查的桶名称'
    )
    
    check_group.add_argument(
        '--names',
        help='要检查的桶名称列表（逗号分隔）'
    )
    
    check_group.add_argument(
        '--health-check',
        action='store_true',
        help='对所有桶进行健康检查'
    )
    
    parser.add_argument(
        '--performance',
        action='store_true',
        help='进行性能测试（仅适用于单桶检查）'
    )
    
    parser.add_argument(
        '--iterations',
        type=int,
        default=10,
        help='性能测试迭代次数 (默认: 10)'
    )
    
    return parser.parse_args()


def main():
    """主函数"""
    args = parse_args()
    
    # 如果指定了 --verbose，覆盖 format 设置
    if args.verbose:
        args.format = 'verbose'
    
    # 创建客户端
    client = BucketHeadClient(
        endpoint_url=args.host,
        access_key=args.access_key,
        secret_key=args.secret_key,
        region=args.region
    )
    
    # 根据格式执行相应操作
    success = False
    
    if args.health_check:
        if args.format == 'simple':
            success = client.health_check_buckets_simple()
        elif args.format == 'verbose':
            success = client.health_check_buckets_verbose()
        elif args.format == 'json':
            success = client.health_check_buckets_json()
    elif args.performance and args.name:
        if args.format == 'simple':
            success = client.performance_test_simple(args.name, args.iterations)
        elif args.format == 'verbose':
            success = client.performance_test_verbose(args.name, args.iterations)
        elif args.format == 'json':
            success = client.performance_test_json(args.name, args.iterations)
    elif args.name:
        if args.format == 'simple':
            success, _ = client.head_single_bucket_simple(args.name)
        elif args.format == 'verbose':
            success, _ = client.head_single_bucket_verbose(args.name)
        elif args.format == 'json':
            success, _ = client.head_single_bucket_json(args.name)
    elif args.names:
        bucket_names = [name.strip() for name in args.names.split(',')]
        if args.format == 'simple':
            success = client.head_multiple_buckets_simple(bucket_names)
        elif args.format == 'verbose':
            success = client.head_multiple_buckets_verbose(bucket_names)
        elif args.format == 'json':
            success = client.head_multiple_buckets_json(bucket_names)
    
    # 设置退出码
    sys.exit(0 if success else 1)


if __name__ == '__main__':
    main()
